﻿using System.Linq;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Log.EventLog;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
using DotNetNuke.ComponentModel;
using DotNetNuke.Services.Cache;


namespace DotNetNuke.Entities.Controllers
{


    public class HostController : ComponentBase<IHostController, HostController>, IHostController
    {


        internal HostController()
        {
        }

        public void Update(ConfigurationSetting config)
        {
            Update(config, true);
        }


        public void Update(ConfigurationSetting config, bool clearCache)
        {
            Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
            try
            {
                if (GetSettings().ContainsKey(config.Key))
                {
                    DataProvider.Instance().UpdateHostSetting(config.Key, config.Value, config.IsSecure, UserController.GetCurrentUserInfo().UserID);
                    objEventLog.AddLog(config.Key, config.Value, DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, EventLogController.EventLogType.HOST_SETTING_UPDATED);
                }
                else
                {
                    DataProvider.Instance().AddHostSetting(config.Key, config.Value, config.IsSecure, UserController.GetCurrentUserInfo().UserID);
                    objEventLog.AddLog(config.Key, config.Value, DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, EventLogController.EventLogType.HOST_SETTING_CREATED);
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);

            }

            if ((clearCache))
            {
                DataCache.ClearHostCache(false);
            }

        }

        public void Update(string key, string value, bool clearCache)
        {
            Update(new ConfigurationSetting
            {
                Key = key,
                Value = value
            }, clearCache);
        }

        public void Update(string key, string value)
        {
            Update(key, value, true);
        }

        public Dictionary<string, ConfigurationSetting> GetSettings()
        {
            return CBO.GetCachedObject<Dictionary<string, ConfigurationSetting>>(new CacheItemArgs(DataCache.HostSettingsCacheKey, DataCache.HostSettingsCacheTimeOut, DataCache.HostSettingsCachePriority), GetSettingsDictionaryCallBack, true);
        }

        public Dictionary<string, string> GetSettingsDictionary()
        {
            return GetSettings().ToDictionary(c => c.Key, c => c.Value.Value);
        }

        public bool GetBoolean(string key)
        {
            return GetBoolean(key, Null.NullBoolean);
        }

        public bool GetBoolean(string key, bool defaultValue)
        {
            Requires.NotNullOrEmpty("key", key);

            bool retValue = false;
            try
            {
                string setting = string.Empty;
                if ((GetSettings().ContainsKey(key)))
                {
                    setting = GetSettings()[key].Value;
                }

                if (string.IsNullOrEmpty(setting))
                {
                    retValue = defaultValue;
                }
                else
                {
                    retValue = (setting.ToUpperInvariant().StartsWith("Y") || setting.ToUpperInvariant() == "TRUE");
                }

            }
            catch (Exception ex)
            {
                //we just want to trap the error as we may not be installed so there will be no Settings
            }
            return retValue;
        }

        public double GetDouble(string key)
        {
            return GetDouble(key, Null.NullDouble);
        }

        public double GetDouble(string key, double defaultValue)
        {
            Requires.NotNullOrEmpty("key", key);

            double retValue = 0;

            if ((!GetSettings().ContainsKey(key) || !double.TryParse(GetSettings()[key].Value, out retValue)))
            {
                retValue = defaultValue;
            }

            return retValue;
        }

        public int GetInteger(string key)
        {
            return GetInteger(key, Null.NullInteger);
        }

        public int GetInteger(string key, int defaultValue)
        {
            Requires.NotNullOrEmpty("key", key);

            int retValue = 0;

            if ((!GetSettings().ContainsKey(key) || !int.TryParse(GetSettings()[key].Value, out retValue)))
            {
                retValue = defaultValue;
            }

            return retValue;
        }

        public string GetString(string key)
        {
            return GetString(key, string.Empty);
        }

        public string GetString(string key, string defaultValue)
        {
            Requires.NotNullOrEmpty("key", key);

            if (!GetSettings().ContainsKey(key) || GetSettings()[key].Value == null)
            {
                return defaultValue;
            }

            return GetSettings()[key].Value;
        }

        private object GetSettingsDictionaryCallBack(CacheItemArgs cacheItemArgs)
        {
            Dictionary<string, ConfigurationSetting> dicSettings = new Dictionary<string, ConfigurationSetting>();
            IDataReader dr = null;
            try
            {
                dr = DataProvider.Instance().GetHostSettings();
                while (dr.Read())
                {
                    string key = dr.GetString(0);
                    ConfigurationSetting config = new ConfigurationSetting();
                    config.Key = key;
                    config.IsSecure = Convert.ToBoolean(dr[2]);
                    if (dr.IsDBNull(1))
                    {
                        config.Value = string.Empty;
                    }
                    else
                    {
                        config.Value = dr.GetString(1);
                    }

                    dicSettings.Add(key, config);
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
            }
            finally
            {
                CBO.CloseDataReader(dr, true);
            }
            return dicSettings;
        }
    }
}
